package week13.week_13_server;
import org.apache.tomcat.jni.Directory;
import sun.reflect.annotation.ExceptionProxy;
import week6.EchoServer;

import javax.print.attribute.standard.Severity;
import java.io.*;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MyCommThread extends Thread {
	Socket s;
	SocketAddress sa = new InetSocketAddress(ServerInfo.serverAddr,ServerInfo.serverDataPort);
	public MyCommThread(Socket s){
		this.s = s;
	}

	public void run(){

		try( //带资源的try
			 ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
			 ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
			 //FileWriter fw = new FileWriter("user.info");
		){
			System.out.println("客户机连接成功！客户机地址和端口："+s.getRemoteSocketAddress());

			while(true){
				try{
					Message msg=(Message)ois.readObject();
					System.out.println(msg);
					if(msg.getMsgType()==MessageType.MSG_REG){
						User user = (User)msg.getContent();
						if(!ServerInfo.containUser(user.getUserName())){
							System.out.println("This is a new user:" + user.getUserName());
							ServerInfo.addUser(user);
							msg.setStatus(Status.SUCCESS);
						} else {
							System.out.println("The user name:" + user.getUserName()+" has already been registered!");
							msg.setStatus(Status.FAIL);
						}
					}
					if(msg.getMsgType()==MessageType.MSG_LOG){
						User user = (User)msg.getContent();
						if(ServerInfo.containUser(user.getUserName()) && ServerInfo.getPassword(user.getUserName()).equals(user.getPassword())){
							System.out.println("The user:" + user.getUserName()+" Login");
							msg.setStatus(Status.SUCCESS);
							ServerInfo.addOnlineUser(user.getUserName(),s);
						} else {
							System.out.println("The user name:" + user.getUserName()+" login fail");
							msg.setStatus(Status.FAIL);
						}
					}
					if (msg.getMsgType()==MessageType.MSG_GET){
						HashMap onlineUser = ServerInfo.getOnlineUser();
						ArrayList arr = new ArrayList();
						for (Object key:onlineUser.keySet()){
							arr.add((String)key);
						}
						msg.setContent(arr);
					}
					if (msg.getMsgType()==MessageType.MSG_TRAN){
						try {
							Socket socket = ServerInfo.getOnlineUser().get(msg.getToUser());
							ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
							os.writeObject(msg);
							os.flush();
							msg.setStatus(Status.SUCCESS);
						}catch (Exception ex){
							msg.setStatus(Status.FAIL);
						}
					}
					if (msg.getMsgType()==MessageType.MSG_PUT_FILE){
						try {
							saveFile(msg);
							Socket socket = ServerInfo.getOnlineUser().get(msg.getToUser());
							ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
							os.writeObject(msg);
							os.flush();
							msg.setStatus(Status.SUCCESS);
						}catch (Exception ex){
							msg.setStatus(Status.FAIL);
						}
					}
					if (msg.getMsgType()==MessageType.MSG_LIST_FILE){
						String path= "D://file/"+msg.getFromUser()+"/";
						File dir = new File(path);
						File[] files = dir.listFiles();
						ArrayList<String> arr = new ArrayList<String>();
						for (File file:files){
							arr.add(file.getName());
						}
						msg.setContent(arr);
					}
//					if (msg.getMsgType()==MessageType.MSG_GET_FILE){
//
//					}
					oos.writeObject(msg);
					oos.flush();
					System.out.println(msg);
					sendOnlineUser();
				}catch (IOException | ClassNotFoundException ex) {

				}
			}

		} catch (IOException ex) {
			ex.printStackTrace();
			System.out.println("异常信息"+ex.getMessage());
		} finally {
			//关闭套接字和流
			try {
				if (s != null)   s.close();
			} catch (IOException ex) {
				System.out.println("异常信息"+ex.getMessage());
			}
		}

	}
	public void sendOnlineUser(){
		HashMap onlineUser = ServerInfo.getOnlineUser();
		ArrayList arr = new ArrayList();
		for (Object key:onlineUser.keySet()){
			arr.add((String)key);
		}
		for (Socket socket: ServerInfo.getOnlineUser().values()){
			try{
				ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
				Message msg = new Message();
				msg.setMsgType(MessageType.MSG_FLUSH);
				msg.setContent(arr);
				os.writeObject(msg);
			}catch (Exception ex){
				ex.printStackTrace();
			}
		}
	}
	public void saveFile(Message msg){
		try {
			DataInputStream dis = new DataInputStream(s.getInputStream());
			String path = "D://file/"+msg.getToUser()+"/";
			InputStream fis = s.getInputStream();
			File file = new File(path);
			if (!file.exists()){
				file.mkdir();
			}
			file = new File(path+msg.getContent());
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len;
			while((len = dis.read(buffer, 0, buffer.length)) != -1) {//读取
				fos.write(buffer, 0, len);
				fos.flush();
			}
			fos.close();
		}catch (Exception ex){
			ex.printStackTrace();
		}
	}

}
